package com.lawliet.example.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.logging.log4j.util.Strings;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Objects;

public class QueryHelper {


    public static  <T> QueryWrapper<T> QueryHelper(T data) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (data == null) {
            return queryWrapper;
        }

        Class<?> clazz = data.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);  // 允许访问私有属性
                Object value = field.get(data);
                if (Objects.isNull(value)) {
                    continue;  // 跳过 null 值
                }

                String fieldName = field.getName();
                String columnName = camelToUnderline(fieldName);  // 驼峰转下划线
                // 根据字段类型决定使用 eq 还是 like
                Class<?> fieldType = field.getType();
                if (fieldType == String.class) {
                    queryWrapper.like(columnName, value);
                }
                //先暂时排除时间格式
                else if(fieldType == Date.class){
                    continue;
                }else {
                    queryWrapper.eq(columnName, value);
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("反射获取属性值失败", e);
            }
        }
        return queryWrapper;
    }

    /**
     * 根据对象的非空字段构造查询条件，默认字符串使用 LIKE，其他类型使用 EQ。
     */
    public static <T> QueryWrapper<T> buildQueryWrapper(T searchObj) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (searchObj == null) return queryWrapper;

        try {
            PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(searchObj.getClass());

            for (PropertyDescriptor pd : descriptors) {
                String fieldName = pd.getName();
                if ("class".equals(fieldName)) continue;

                Object value = PropertyUtils.getSimpleProperty(searchObj, fieldName);
                if (Objects.isNull(value)) continue;

                String columnName = camelToUnderline(fieldName);
                Class<?> fieldType = pd.getPropertyType();

                if (fieldType == String.class) {
                    if (Strings.isNotEmpty((String) value)) {
                        queryWrapper.like(columnName, value);
                    }
                } else if (fieldType == Date.class) {
                    // 可按需加入范围查询字段 _begin/_end 的处理逻辑
                    continue;
                } else {
                    queryWrapper.eq(columnName, value);
                }
            }
            queryWrapper.orderByDesc("create_time");

        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException("属性解析失败", e);
        }

        return queryWrapper;
    }


    /**
     * 根据对象的非空字段构造查询条件，默认字符串使用 LIKE，其他类型使用 EQ。
     */
    public static <T> QueryWrapper<T> buildQueryWrapper(T searchObj,Date start, Date end) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if (searchObj == null) return queryWrapper;

        try {
            PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(searchObj.getClass());

            for (PropertyDescriptor pd : descriptors) {
                String fieldName = pd.getName();
                if ("class".equals(fieldName)) continue;

                Object value = PropertyUtils.getSimpleProperty(searchObj, fieldName);
                if (Objects.isNull(value)) continue;

                String columnName = camelToUnderline(fieldName);
                Class<?> fieldType = pd.getPropertyType();

                if (fieldType == String.class) {
                    if (Strings.isNotEmpty((String) value)) {
                        queryWrapper.like(columnName, value);
                    }
                } else if (fieldType == Date.class) {
                    // 可按需加入范围查询字段 _begin/_end 的处理逻辑
                    continue;
                } else {
                    queryWrapper.eq(columnName, value);
                }
            }


            // 👇 添加时间范围（这里假设统一按 create_time 过滤）
            if (start != null) {
                queryWrapper.ge("create_time", start);
            }
            if (end != null) {
                queryWrapper.le("create_time", end);
            }
            queryWrapper.orderByDesc("create_time");

        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException("属性解析失败", e);
        }

        return queryWrapper;
    }

    /**
     * 驼峰命名转下划线（userName → user_name）
     */
    private static String camelToUnderline(String camelCase) {
        return StringUtils.camelToUnderline(camelCase);
    }

}
